package com.feishi.core.socket.common;

import com.feishi.core.analytic.assembler.BaseAssembler;
import com.feishi.core.socket.common.filter.SocketFilter;
import com.feishi.core.socket.common.lifecycle.SocketRequest;
import com.feishi.core.socket.common.lifecycle.SocketSession;

import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-3-28 14:47
 **/
public abstract class SocketHandler<T extends BaseAssembler>  implements SocketListener<T>{

    protected boolean connected;
    protected SocketSession<T> session;

    /**
     * 连接未建立前缓存数据
     * */
    protected List msg=new ArrayList();

    public void  write(byte[] bytes){
        if(connected){
            writeAndFlush(bytes);
        }else{
            msg.add(msg);
        }
    }
    public void  onConnect(SocketAddress address){
        this.connected=true;
    }
    public void  onDisconnect(SocketAddress address){
        this.connected=false;
    }

    public boolean isConnected() {
        return connected;
    }

    public void setConnected(boolean connected) {
        this.connected = connected;
    }

    public SocketSession getSession() {
        return session;
    }

    public void setSession(SocketSession<T> session) {
        this.session = session;
        this.session.setSocketHandler(this);
    }

    protected abstract void writeAndFlush(byte[] bytes);

    @Override
    public void onMsg(T msg) {
        SocketRequest request=new SocketRequest(session);
        List<SocketFilter<T>> list=session.getApplication().getFilters();
        for (SocketFilter<T> filter : list) {
            if(filter.doFilter(request,msg)){
                break;
            }
        }
    }
}
